//
//  BillingDetailsViewController.m
//  PrintPort
//
//  Created by 华谕 on 2017/11/14.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "BillingDetailsViewController.h"
#import "BillDetaModel.h"

static NSString *cellPath = @"BillingDetailCell";
@interface BillingDetailsViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIButton *leftBtn;
    UIButton *rightBtn;
    UIView *lineView;
}
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSArray *BillFirstAry;
@property (nonatomic, strong)NSArray *BillSecondAry;
@property (nonatomic, strong)NSMutableDictionary *BillFirstDic;
@property (nonatomic, strong)NSMutableDictionary *BillSecondDic;
@property (nonatomic, assign)NSInteger BillType;
@property (nonatomic, assign)NSInteger leftPage;
@property (nonatomic, assign)NSInteger rightPage;
@property (nonatomic, strong)NSString *newtime;
@end

@implementation BillingDetailsViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self huoqushijian];
    _BillType = 0;
    _leftPage = 0;
    _rightPage = 0;
    _BillFirstDic = [NSMutableDictionary dictionaryWithCapacity:0];
    _BillSecondDic = [NSMutableDictionary dictionaryWithCapacity:0];
    [self creatUI];
    [self requestUserWalletInfoList];
}

- (void)creatUI
{
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor = BacksColor;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"账单明细";
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40*displaywidth)];
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    NSArray *titAry = @[@"一类积分",@"二类积分"];
    CGFloat W = (SCREEN_WIDTH-1*displaywidth)/2;
    for (int i = 0; i < titAry.count; i++)
    {
        UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(i*(W + 1*displaywidth), 0, W, 39*displaywidth) ImageName:nil Target:self Action:@selector(intiveTypeAction:) Title:titAry[i] Font:13.0];
        [btn setTitleColor:RGB(77, 77, 77) forState:UIControlStateNormal];
        if (i == _BillType)
        {
            [btn setTitleColor:ThemeColor forState:UIControlStateNormal];

        }
        btn.tag = 100+i;
        [topView addSubview:btn];
        if (i != 1)
        {
            UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(W+(W+1*displaywidth)*i, 0, 1*displaywidth, 40*displaywidth)];
            lineview.backgroundColor = LinesColor;
            [topView addSubview:lineview];
        }
        if (i == 0)
        {
            leftBtn = btn;
        }
        else
        {
            rightBtn = btn;
        }
    }
    lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 39*displaywidth, W, 1*displaywidth)];
    lineView.backgroundColor = LinesColor;
    [topView addSubview:lineView];
    CGFloat heightX = 0;
    if (SCREEN_HEIGHT == 812)
    {
        heightX = 34;
    }
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 40*displaywidth, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-40*displaywidth-heightX) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.backgroundColor = BacksColor;
    [self.view addSubview:_tableview];
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFootData)];
    self.tableview.mj_footer.automaticallyHidden = YES;
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    
}

- (void)intiveTypeAction:(UIButton *)btn
{
    _BillType = btn.tag-100;
    if (_BillType == 0)
    {
        [leftBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
        [rightBtn setTitleColor:RGB(77, 77, 77) forState:UIControlStateNormal];

    }
    else
    {
        [leftBtn setTitleColor:RGB(77, 77, 77) forState:UIControlStateNormal];
        [rightBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    }
    lineView.frame = CGRectMake(SCREEN_WIDTH/2*_BillType, 39*displaywidth, SCREEN_WIDTH/2, 1*displaywidth);
    [self requestUserWalletInfoList];
}

- (void)loadNewHeaderData
{
    if (_BillType == 0)
    {
        _leftPage = 0;
    }
    else
    {
        _rightPage = 0;
    }
    [self requestUserWalletInfoList];
    
}

- (void)loadMoreFootData
{
    if (_BillType == 0)
    {
        _leftPage++;
    }
    else
    {
        _rightPage++;
    }
    [self requestUserWalletInfoList];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_BillType == 0)
    {
        return _BillFirstAry.count;
    }
    else
    {
        return _BillSecondAry.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_BillType == 0)
    {
        NSArray *billary = [_BillFirstDic objectForKey:_BillFirstAry[section]];
        return billary.count;
    }
    else
    {
        NSArray *billary = [_BillSecondDic objectForKey:_BillSecondAry[section]];
        return billary.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1*displaywidth)];
    lineview.backgroundColor = LinesColor;
    [cell.contentView addSubview:lineview];
    BillDetaModel *Model;
    if (_BillType == 0)
    {
        if (_BillFirstDic.count > 0)
        {
            NSArray *dataAry = [_BillFirstDic objectForKey:_BillFirstAry[indexPath.section]];
            Model = dataAry[indexPath.row];
        }
    }
    else
    {
        if (_BillSecondDic.count > 0)
        {
            NSArray *dataAry = [_BillSecondDic objectForKey:_BillSecondAry[indexPath.section]];
            Model = dataAry[indexPath.row];
        }
    }
    if (Model)
    {
//        NSDictionary *dic = @{@"1":@"充值",@"10":@"购买",@"20":@"激励金",@"30":@"回购",@"40":@"直接奖励",@"41":@"间接奖励"};
        NSString *name = Model.remark;
//        if ([dic.allKeys containsObject:Model.type])
//        {
//            name = [dic objectForKey:Model.type];
//        }
        UILabel *namelab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, SCREEN_WIDTH-150*displaywidth, 25*displaywidth) Font:14.0 Text:name Color:RGB(77, 77, 77)];
        [cell.contentView addSubview:namelab];
        NSString *timeStr = Model.createDtm;
        if (Model.createDtm.length > 16)
        {
            NSString *newtimeStr = [Model.createDtm substringToIndex:10];
            newtimeStr = [newtimeStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
            if ([newtimeStr isEqualToString:_newtime])
            {
                NSString *minustr = [Model.createDtm substringWithRange:NSMakeRange(11, 5)];
                timeStr = [NSString stringWithFormat:@"今天   %@",minustr];
            }
            else if ([newtimeStr integerValue]+1==[_newtime integerValue])
            {
                NSString *minustr = [Model.createDtm substringWithRange:NSMakeRange(11, 5)];
                timeStr = [NSString stringWithFormat:@"昨天   %@",minustr];
            }
            else
            {
                timeStr = [Model.createDtm substringToIndex:16];
            }
        }
        UILabel *timelab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 30*displaywidth, SCREEN_WIDTH-150*displaywidth, 25*displaywidth) Font:12.0 Text:timeStr Color:RGB(173, 173, 173)];
        [cell.contentView addSubview:timelab];
        NSString *moneyStr = Model.money;
        UIColor *moneyColor = RGB(77, 77, 77);
        if (![Model.money containsString:@"-"])
        {
            moneyStr = [NSString stringWithFormat:@"+%@",moneyStr];
            moneyColor = RGB(255, 111, 28);
        }
        UILabel *moneyLab = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH- 150*displaywidth, 10*displaywidth, 130*displaywidth, 40*displaywidth) Font:14.0 Text:moneyStr Color:moneyColor];
        moneyLab.textAlignment = NSTextAlignmentRight;
        [cell.contentView addSubview:moneyLab];
        
        
    }
   
    return cell;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30*displaywidth)];
    myView.backgroundColor = BacksColor;
    UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, 20*displaywidth, 20*displaywidth) ImageName:@"rili"];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    [myView addSubview:imgView];
    NSString *nowMonth = [_newtime substringToIndex:6];
    NSString *monthStr = _BillFirstAry[section];
    if (_BillType == 1)
    {
        monthStr = _BillSecondAry[section];
    }
    if ([[monthStr substringToIndex:6] isEqualToString:nowMonth])
    {
        monthStr = @"本月";
    }
    else
    {
        if ([[monthStr substringToIndex:4] isEqualToString:[nowMonth substringToIndex:4]])
        {
            monthStr = [monthStr substringWithRange:NSMakeRange(4, 2)];

        }
        else
        {
             NSString *yearStr = [monthStr substringWithRange:NSMakeRange(0, 4)];
             NSString *month = [monthStr substringWithRange:NSMakeRange(4, 2)];
             monthStr = [NSString stringWithFormat:@"%@-%@",yearStr,month];

        }
        
    }
    UILabel *namelab = [ZCControl createLabelWithFrame:CGRectMake(45*displaywidth, 0, 120*displaywidth, 30*displaywidth) Font:13.0 Text:monthStr Color:ThemeColor];
    [myView addSubview:namelab];
    return myView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60*displaywidth;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30*displaywidth;
}

- (void)requestUserWalletInfoList
{
    WEAKSELF;
    NSString *typeStr = @"1";
    NSString *pageStr = [NSString stringWithFormat:@"%ld",_leftPage];
    if (_BillType == 1)
    {
        typeStr = @"2";
        pageStr = [NSString stringWithFormat:@"%ld",_rightPage];
    }
    NSDictionary *dic = @{@"page":pageStr,
                          @"size":@"10",
                          @"moneyType":typeStr
                          };
    [HYBaseHandler requestUserWalletInfoListParmers:dic Success:^(id obj)
    {
        if ([obj server_Getcodecheck])
        {
            NSArray *billAry = [BillDetaModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
            if (_BillType == 0 && _leftPage == 0)
            {
                [weakSelf.BillFirstDic removeAllObjects];
            }
            if (_BillType == 1 && _rightPage == 0)
            {
                [weakSelf.BillFirstDic removeAllObjects];

            }
            if (_BillType == 0)
            {
                for (BillDetaModel *model in billAry)
                {
                    if (model.createDtm.length > 7)
                    {
                        NSString *timeStr = [model.createDtm substringToIndex:7];
                        timeStr = [timeStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
                        if ([_BillFirstDic.allKeys containsObject:timeStr])
                        {
                            NSMutableArray *bigAry = [NSMutableArray arrayWithCapacity:0];
                            NSArray *lastAry = [_BillFirstDic objectForKey:timeStr];
                            [bigAry addObjectsFromArray:lastAry];
                            [bigAry addObject:model];
                            [_BillFirstDic setObject:bigAry forKey:timeStr];
                        }
                        else
                        {
                            NSMutableArray *bigAry = [NSMutableArray arrayWithCapacity:0];
                            [bigAry addObject:model];
                            [_BillFirstDic setObject:bigAry forKey:timeStr];

                        }

                    }
                }
                NSArray *keyAry = _BillFirstDic.allKeys;
                NSComparator finderSort = ^(id string1,id string2){
                    
                    if ([string1 integerValue] < [string2 integerValue]) {
                        return (NSComparisonResult)NSOrderedDescending;
                    }else if ([string1 integerValue] > [string2 integerValue]){
                        return (NSComparisonResult)NSOrderedAscending;
                    }
                    else
                        return (NSComparisonResult)NSOrderedSame;
                };
                
                //数组排序：
                weakSelf.BillFirstAry = [keyAry sortedArrayUsingComparator:finderSort];
               
            }
            else
            {
                for (BillDetaModel *model in billAry)
                {
                    if (model.createDtm.length > 7)
                    {
                        NSString *timeStr = [model.createDtm substringToIndex:7];
                        timeStr = [timeStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
                        if ([_BillSecondDic.allKeys containsObject:timeStr])
                        {
                            NSMutableArray *bigAry = [NSMutableArray arrayWithCapacity:0];
                            NSArray *lastAry = [_BillSecondDic objectForKey:timeStr];
                            [bigAry addObjectsFromArray:lastAry];
                            [bigAry addObject:model];
                            [_BillSecondDic setObject:bigAry forKey:timeStr];
                        }
                        else
                        {
                            NSMutableArray *bigAry = [NSMutableArray arrayWithCapacity:0];
                            [bigAry addObject:model];
                            [_BillSecondDic setObject:bigAry forKey:timeStr];
                            
                        }
                        
                    }
                }
                NSArray *keyAry = _BillSecondDic.allKeys;
                NSComparator finderSort = ^(id string1,id string2){
                    
                    if ([string1 integerValue] < [string2 integerValue]) {
                        return (NSComparisonResult)NSOrderedDescending;
                    }else if ([string1 integerValue] > [string2 integerValue]){
                        return (NSComparisonResult)NSOrderedAscending;
                    }
                    else
                        return (NSComparisonResult)NSOrderedSame;
                };
                
                //数组排序：
                weakSelf.BillSecondAry = [keyAry sortedArrayUsingComparator:finderSort];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
           
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];

    } failed:^(NSError *error) {
        
    }];
}




- (void)huoqushijian
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYYMMdd"];
    _newtime = [formatter stringFromDate:[NSDate date]];
    NSLog(@"----------%@----------",_newtime);
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
